<template>
  <div class="app-container">
    <el-dialog
      :title="targetTitle"
      style="min-width: 500px; width: auto"
      size="small"
      :visible.sync="showDelDialog"
      @close="closeDialogHandler"
    >
      <el-button @click="showDelDialog = false" size="small">否</el-button>
      <el-button type="primary" @click="delHandler" size="small">是</el-button>
    </el-dialog>
    <el-dialog
      :title="targetTitle"
      width="700"
      size="small"
      :visible.sync="showAddDialog"
      @close="closeDialogHandler"
    >
      <div style="min-height: 500px; height: auto">
        <doc-add :pid="pid" v-on:close="closeDialogHandler"></doc-add>
      </div>
    </el-dialog>
    <el-dialog
      :title="targetTitle"
      width="700"
      size="small"
      :visible.sync="showEditDialog"
      @close="closeDialogHandler"
    >
      <div style="height: auto">
        <doc-edit
          :target="target"
          type="1"
          v-on:close="closeDialogHandler"
        ></doc-edit>
      </div>
    </el-dialog>
    <div style="margin-bottom: 16px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="item in pageParent" :key="item.id">
          <el-button
            type="text"
            :disabled="item.disable"
            style="padding-bottom: 0px"
            >{{ item.name }}
          </el-button>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 操作表单 -->
    <div class="op-form">
      <el-form :inline="formInline" class="demo-ruleForm">
        <div>
          <el-form-item label="文档名称" label-width="80px">
            <el-input
              v-model="searchKey"
              placeholder="要搜索的文档名称"
              @keyup.enter.native="seachHandler"
              style="width: 300px"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="seachHandler"
                >搜索</el-button
              >
            </el-input>
          </el-form-item>
          <el-form-item label="状态" label-width="50px">
            <el-select placeholder="选择文件状态" v-model="status">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属主题">
            <el-select style="width: 100%" v-model="theme_id">
              <el-option label="所有主题" value="0"></el-option>
              <el-option
                v-for="option in options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="来源">
            <el-select style="width: 100%" v-model="fromType">
              <el-option
                v-for="option in fromOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="border-top: 1px dashed #cccccc; padding-top: 10px">
          <el-button type="primary" size="small" @click="onAdd"
            >添加文档</el-button
          >
          <el-button type="primary" size="small" @click="onFresh"
            >刷新页面</el-button
          >
        </div>
      </el-form>
    </div>
    <el-table
      :data="list"
      v-loading.body="loading"
      @sort-change="sortHandler"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        align="center"
        fixed="left"
        sortable="true"
        prop="id"
        label="ID"
        width="95"
      >
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="文档名" width="420" align="center">
        <template slot-scope="scope">
          <div>
            <el-tag type="info">
              <svg-icon icon-class="file_pdf"></svg-icon>
              <el-tooltip placement="top" :content="scope.row.name">
                <span
                  style="
                    width: 100px;
                    overflow: hidden;
                    text-overflow: ellipse；;
                  "
                >
                  <a :href="scope.row.online_url" target="_blank">{{
                    scope.row.name
                  }}</a>
                </span>
              </el-tooltip>
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="主题"
        sortable="true"
        prop="v_count"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.theme_name }}
        </template>
      </el-table-column>
      <el-table-column label="作者" width="110" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.from_type == 1">系统</span>
          <span v-else> 用户 </span>
        </template>
      </el-table-column>
      <el-table-column
        label="页数"
        sortable="true"
        prop="page_count"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.page_count > 0">{{ scope.row.page_count }}</div>
          <div v-else>
            <!-- <el-button size="mini" @click="onDoc2Png(scope.row)" v-else>分解文件</el-button> -->
            <div v-if="scope.row.d2p_taskid == 0">
              <el-button size="mini" @click="onDoc2Png(scope.row)"
                >分解文件</el-button
              >
            </div>
            <div style="margin-top: 10px" v-else>
              <el-progress
                :text-inside="true"
                :stroke-width="18"
                :percentage="scope.row.d2p_progress"
                status="success"
              ></el-progress>
            </div>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="阅读数" sortable="true" prop="v_count" width="100" align="center">
        <template slot-scope="scope">
          {{scope.row.read_count}}
        </template>
      </el-table-column>
      <el-table-column label="下载数" sortable="true" prop="dw_count" width="100" align="center">
        <template slot-scope="scope">
          {{scope.row.download_count}}
        </template>
      </el-table-column> -->
      <el-table-column
        class-name="status-col"
        label="推荐"
        width="110"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.is_recommend == 1">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        class-name="status-col"
        label="状态"
        width="110"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
          <el-tag type="danger" v-else>已下线</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        sortable="true"
        prop="create_time"
        label="发布时间"
        width="200"
      >
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="update_time"
        label="操作"
        width="120"
      >
        <template slot-scope="scope">
          <span>
            <el-dropdown
              size="small"
              split-button
              type="primary"
              @command="opHandler"
            >
              操作
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="scope.row">
                  <span>{{
                    scope.row.is_recommend == "0" ? "推荐" : "取消推荐"
                  }}</span>
                </el-dropdown-item>
                <el-dropdown-item :command="scope.row.cmd_del">
                  <span>删除</span>
                </el-dropdown-item>
                <el-dropdown-item :command="scope.row.cmd_online">
                  <span v-if="scope.row.status == 1">下线</span>
                  <span v-else>上线</span>
                </el-dropdown-item>
                <el-dropdown-item :command="scope.row.cmd_edit">
                  <span>编辑</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px; margin-left: -10px">
      <el-pagination
        ref="pagination"
        background
        :page-size="pageSize"
        :current-page="page"
        :pager-count="21"
        @current-change="pageChange"
        layout="prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getOptions } from "@/api/theme";
import {
  getList,
  setStatus,
  setRecommand,
  pdf2png,
  checkTask,
  addQrCode,
  upFilePageCount,
  del,
} from "@/api/report";
import DocAdd from "./component/docAdd";
import DocEdit from "./component/docEdit";
import { clearInterval, setInterval } from "timers";
export default {
  data() {
    return {
      // 对话框
      showDelDialog: false,
      showAddDialog: false,
      showEditDialog: false,
      loopId: 0,
      d2pTaskId: 0,
      // 目标信息
      target: undefined,
      targetId: 0,
      targetTitle: "",
      formInline: true,
      list: [],
      options: [],
      loading: true,
      pageSize: 0,
      total: 0,
      executeQuery: false,
      pageParent: [
        {
          id: 0,
          name: "最顶级",
          query: undefined,
          disable: true,
        },
      ],
      page: 1,
      searchKey: "",
      status: "1",
      fromType: "0",
      fromOptions: [
        {
          value: "0",
          label: "全部",
        },
        {
          value: "1",
          label: "系统",
        },
        {
          value: "2",
          label: "用户",
        },
      ],
      statusOptions: [
        {
          value: "0",
          label: "已下线",
        },
        {
          value: "1",
          label: "正常",
        },
        {
          value: "2",
          label: "全部",
        },
      ],
      theme_id: "0",
      pid: "0",
      // pThemeId: "0",
      osc: "DESC",
      orderKey: "id",
    };
  },
  components: {
    "doc-add": DocAdd,
    "doc-edit": DocEdit,
  },
  watch: {
    executeQuery: function (nv, ov) {
      if (nv) {
        // 如果为true, 则执行查询
        this.fetchData();
      }
    },
    theme_id: function (nv, ov) {
      console.log("new theme_id:" + nv);
      this.executeQuery = true;
    },
  },
  computed: {
    disableBreadcrumbBtn(idx) {
      if (idx == this.pageParent.length - 1) {
        return true;
      } else {
        return false;
      }
    },
  },
  mounted() {
    // 重置数据, 每次进入页面的时候
    this.searchKey = "";
    this.pid = "0"; //  没有父ID
    this.theme_id = "0"; // 主题ID
    // this.pThemeId = '0' // 父ID的主题ID
    this.osc = "DESC"; //  降序
    this.orderKey = "id"; // 按id排序
    this.status = "1"; //  系统上传
    this.page = 1; //  第一页
    this.pageParent[0].query = this.buildListQuery(0);
    // 载入主题分类
    this.loadThemeOption();
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.loading = true;
      let query = this.buildListQuery();
      getList(query)
        .then((res) => {
          console.log(res);
          this.pageSize = res.page_size;
          this.total = res.total;
          this.loading = false;
          this.executeQuery = false;
          this.list = res.items;
          console.log("pize:" + this.pageSize + ", total:" + this.total);
          // 更新分页器的内部当前页
          this.$refs.pagination.internalCurrentPage = this.page;
        })
        .catch((err) => {
          this.loading = false;
          this.executeQuery = false;
        });
    },
    // 获取主题选项
    loadThemeOption() {
      // 请求API获取
      getOptions().then((res) => {
        this.options = res.items;
      });
    },
    opHandler(command) {
      console.log(typeof command);
      if (typeof command === "object") {
        console.log("推荐：", command);
        let item = command;
        setRecommand(item.is_recommend == "0" ? 1 : 0, item.id).then(
          (response) => {
            this.fetchData();
          }
        );
        return;
      }
      const cmdInfo = command.split(":");

      switch (cmdInfo[0]) {
        case "online":
          this.targetId = cmdInfo[1];
          // 查找名字
          let target = this.findItemById(this.targetId);
          this.targetTitle = '文件: "' + target.name + '" ';
          if (target.status == 0) {
            this.targetTitle += "上线";
          } else {
            this.targetTitle += "下线";
          }
          // 执行命令
          this.statusHandler();
          break;
        case "del":
          this.targetId = cmdInfo[1];
          this.target = this.findItemById(this.targetId);
          console.log(this.target);
          this.targetTitle =
            '文件: "' +
            this.target.name +
            '" 将被永久删除, 其OSS资源也将一并删除, 请谨慎操作 !!!';
          // 来自
          this.showDelDialog = true;
          break;
        case "edit":
          this.targetId = cmdInfo[1];
          this.target = this.findItemById(this.targetId);
          this.targetTitle = "编辑文件";
          // 来自
          this.showEditDialog = true;
          break;
        default:
          console.log("no law command");
      }
    },
    sortHandler(sortInfo) {
      this.orderKey = sortInfo.prop;
      if (sortInfo.order === "descending") {
        this.osc = "DESC";
      } else {
        this.osc = "ASC";
      }
      this.executeQuery = true;
    },
    showSubList(item) {
      // 获取数据
      let lastIdx = this.pageParent.length - 1;
      let nowQuery = this.buildListQuery();
      this.pageParent[lastIdx].query = nowQuery;
      this.pageParent[lastIdx].disable = false;

      // 更新页面刷新参数
      this.pid = item.item_id;
      this.pThemeId = item.theme_id;
      this.page = 1;
      this.ftype = "0";
      this.searchKey = "";
      let newQuery = this.buildListQuery();
      this.pageParent.push({
        id: item.item_id,
        query: newQuery,
        name: item.name,
        disable: true,
      });
      this.executeQuery = true;
    },
    pageChange(page) {
      this.page = page;
      this.executeQuery = true;
    },
    // 上|下线处理
    statusHandler() {
      setStatus(1, this.targetId).then((response) => {
        this.fetchData();
        this.targetId = 0;
        this.targetName = "";
        this.targetType = 0;
        this.showDelDialog = false;
      });
    },
    // 上|下线处理
    delHandler() {
      del(this.targetId).then((response) => {
        this.fetchData();
        this.targetId = 0;
        this.targetName = "";
        this.targetType = 0;
        this.showDelDialog = false;
      });
    },
    // 搜索
    seachHandler() {
      this.fetchData();
    },
    // 在列表中查找项目
    findItemById(id) {
      let target = undefined;
      // 查找名字
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].id == this.targetId) {
          target = this.list[i];
          break;
        }
      }
      return target;
    },
    buildListQuery() {
      // 按当前方式创建Query对象
      return {
        name: this.searchKey,
        page: this.page,
        status: this.status,
        theme_id: this.theme_id,
        from_type: this.fromType,
      };
    },
    closeDialogHandler() {
      this.showDelDialog = false;
      this.showAddDialog = false;
      this.targetId = 0;
      this.targetTitle = "";
      // this.targetId = 0
      // this.targetName = ''
      this.fetchData();
    },
    onAdd() {
      this.showAddDialog = true;
      this.targetTitle = "添加新文件";
    },
    onFresh() {
      // 查询数据
      this.fetchData();
    },
    onAddQrCode(id) {
      // 调用API生成
      addQrCode(id)
        .then((res) => {
          this.$message.success("生成二维码成功!!!");
          this.executeQuery = true;
        })
        .catch((error) => {
          this.$message.success("生成二维码失败!!!");
        });
    },
    onDoc2Png(doc) {
      let fileInfo = doc.online_url.split("https://plancos.seedsufe.com/");
      let onlineUrl = fileInfo[1];
      let pageDir = "pages/" + onlineUrl.split(".")[0];
      // 开始执行拆分操作
      pdf2png(onlineUrl, pageDir + "/").then((res) => {
        this.$message.info("文档:" + doc.name + "转化任务开始...");
        doc.d2p_taskid = res.task_id;
        doc.totalPage = res.totalPage;
      });
      this.onCheckTask(doc);
    },
    // 定时检查
    onCheckTask(doc) {
      // 定时检查
      doc.d2p_loopid = setInterval(() => {
        // 验证文件是否拆分完成
        if (doc.d2p_taskid) {
          /** 此处是假进度, 阿里云当前的IMM转化服务无法提供细粒度的进度返回,
           * 后期IMM支持细粒度进度返回的时候, 在checkTask的响应处理函数中
           * 同步转化进度
           */
          if (doc.d2p_progress < 99) {
            doc.d2p_progress += 1;
          }
          // 检查转化任务的处理进度
          checkTask(doc.d2p_taskid).then((res) => {
            let msg = "";
            switch (res.status) {
              case "Finished":
                clearInterval(this.loopId);
                // 清理任务信息
                doc.d2p_loopid = 0;
                doc.d2p_taskid = 0;
                doc.d2p_progress = 100;

                // doc.page_count = res.page_count
                // 提示任务成功
                msg = "文档:" + doc.name + " 转换成功";
                this.$message.success(msg);
                // 更新当前文档的页码
                upFilePageCount(doc.id, doc.totalPage).then((res) => {
                  this.executeQuery = true;
                });
                break;
              case "Failed":
                clearInterval(this.loopId);
                doc.d2p_loopid = 0;
                doc.d2p_taskid = 0;
                doc.d2p_progress = 100;
                msg = "文档:" + doc.name + " 转换失败";
                this.$message.error(msg);
                break;
            }
          });
        }
      }, 1000);
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.avatar-img {
  width: 40px;
  height: 40px;
  border: 2px solid #409eff;
  border-radius: 5px;
}
.el-button--text {
  padding-top: 0px;
  color: #7c796e;
}
.op-form {
  background: #f5f9ff;
  border: 1px dashed #cccccc;
  border-radius: 5px;
  padding: 10px;
  margin-bottom: 12px;
}
.el-form-item {
  margin-bottom: 10px;
}
</style>

